package com.example.yuntiku.Servlet;

import com.example.yuntiku.Service.*;
import com.example.yuntiku.dao.impl.ExamanwerDaoImpl;
import com.example.yuntiku.dao.impl.PagerquestionDaoImpl;
import com.example.yuntiku.dao.impl.QuestionDaoImpl;
import com.example.yuntiku.dao.impl.RecordDaoImpl;
import com.example.yuntiku.entity.*;
import com.example.yuntiku.entity.Record;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

//使用三元
@WebServlet(name = "PagerinsertServlet", value = "/PagerinsertServlet")
public class PagerinsertServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //调用写好的方法用于添加试卷信息
        PagerService pagerService = new PagerService();
        //调用写好的方法，用于查询试卷名称
        CurriculumService curriculumService = new CurriculumService();

        //获取用户选中的题目类别
        String cid = request.getParameter("cid");
        //获取这套卷子的题数
        String tote = request.getParameter("tote");
        //获取是自测还是考试
        String ptype = request.getParameter("ptype");
        //登录来了从作用域掉
        int cpId = 2;
        //用户id：登录来了从作用域掉
        User user = (User) request.getSession().getAttribute("user");
        int cjr = user.getUid();

        //试卷编号
        int i=0;

        //一级类编号
        int yijil;

        //二级类编号
        int erjlbh;

        //获取到试卷名称
        Curriculum curriculum = curriculumService.selectName(Integer.parseInt(cid));
        String name = null;
        //curriculum.getCtype()==2表示它是二级知识点
        int ip = curriculum.getCtype();
        if(curriculum.getCtype()==2 || curriculum.getCtype()==1){
            name = curriculum.getCsection();

            yijil=curriculum.getCid();
            //整合数据进行添加
            Pager pager = new Pager();
            pager.setPname(name);
            pager.setDuration(null);
            pager.setTote(Integer.parseInt(tote));
            pager.setSumscore(0);
            pager.setScore(0);
            pager.setProductid(cpId);
            pager.setTeacherid(cjr);
            pager.setPtype(Integer.parseInt(ptype));
            i = pagerService.pagerinsert(pager);



            //查询做过的题目
            QuestionDaoImpl questionDao = new QuestionDaoImpl();
            Record record = questionDao.selectRecordlist(String.valueOf(cjr),String.valueOf(yijil),null);

            //获取做过的题目后将这些题目排除再去查找符合章节条件的题目
            PagerquestionDaoImpl pagerquestionDao = new PagerquestionDaoImpl();
            PagerQuestion pagerquestion = new PagerQuestion();

            if(record!=null && record.getRecordlist()!=null){
                String[] recordlistArray = record.getRecordlist().split(",");
                List<Question> list = questionDao.selectQuestion(recordlistArray,String.valueOf(curriculum.getFknowledge()),String.valueOf(curriculum.getCid()),null, Integer.parseInt(tote));
                for (Question question : list) {
                    pagerquestion.setPagerid(i);
                    pagerquestion.setQuestionid(question.getId());
                    pagerquestionDao.pagerquestioninsert(pagerquestion);
                }
                request.setAttribute("curriculum",list);//题目集合
                request.setAttribute("shujmc",name);//试卷名称名称
                request.setAttribute("shijId",i);//试卷Id
            }else{
                String[] r={"0"};
                List<Question> list;
                if(curriculum.getCtype()==2){
                    list = questionDao.selectQuestion(r,String.valueOf(curriculum.getFknowledge()),String.valueOf(curriculum.getCid()),null, Integer.parseInt(tote));
                }else{
                    list = questionDao.selectQuestion(r,String.valueOf(curriculum.getCid()),null,null, Integer.parseInt(tote));
                }
                for (Question question : list) {
                    System.out.println(question.getId());
                    pagerquestion.setPagerid(i);
                    pagerquestion.setQuestionid(question.getId());
                    pagerquestionDao.pagerquestioninsert(pagerquestion);
                }
                request.setAttribute("shifyfj",curriculum.getFknowledge());//
                request.setAttribute("curriculum",list);
                request.setAttribute("shujmc",name);
                request.setAttribute("shijId",i);
            }
        }else{
            Curriculum curriculum1 = curriculumService.selectName(curriculum.getFknowledge());
            name=curriculum1.getCsection()+">"+curriculum.getCsection();
            yijil=curriculum1.getCid();
            erjlbh=curriculum.getCid();
            int zhisd = curriculum1.getFknowledge();
            //整合数据进行添加
            Pager pager = new Pager();
            pager.setPname(name);
            pager.setDuration(null);
            pager.setTote(Integer.parseInt(tote));
            pager.setSumscore(0);
            pager.setScore(0);
            pager.setProductid(cpId);
            pager.setTeacherid(cjr);
            pager.setPtype(Integer.parseInt(ptype));
            i = pagerService.pagerinsert(pager);

            //查询做过的题目
            QuestionDaoImpl questionDao = new QuestionDaoImpl();
            Record record = questionDao.selectRecordlist(String.valueOf(cjr),String.valueOf(yijil), String.valueOf(erjlbh));

            //获取做过的题目后将这些题目排除再去查找符合章节条件的题目
            PagerquestionDaoImpl pagerquestionDao = new PagerquestionDaoImpl();
            PagerQuestion pagerquestion = new PagerQuestion();
            if(record!=null && record.getRecordlist()!=null){
                String[] recordlistArray = record.getRecordlist().split(",");
                List<Question> list = questionDao.selectQuestion(recordlistArray,String.valueOf(zhisd),String.valueOf(yijil),String.valueOf(erjlbh), Integer.parseInt(tote));
                for (Question question : list) {
                    pagerquestion.setPagerid(i);
                    pagerquestion.setQuestionid(question.getId());
                    pagerquestionDao.pagerquestioninsert(pagerquestion);
                }
                request.setAttribute("curriculum",list);
                request.setAttribute("shujmc",name);
                request.setAttribute("shijId",i);
            }else{
                String[] r={"0"};
                List<Question> list = questionDao.selectQuestion(r,String.valueOf(zhisd),String.valueOf(yijil),String.valueOf(erjlbh), Integer.parseInt(tote));
                for (Question question : list) {
                    System.out.println(question.getId());
                    pagerquestion.setPagerid(i);
                    pagerquestion.setQuestionid(question.getId());
                    pagerquestionDao.pagerquestioninsert(pagerquestion);
                }
                request.setAttribute("curriculum",list);
                request.setAttribute("shujmc",name);
                request.setAttribute("shijId",i);
            }
        }
        request.getRequestDispatcher("ShuTiYM.jsp").forward(request,response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        ExamService examService = new ExamService();

        //处理乱码让中文可以输出
        request.setCharacterEncoding("UTF-8");

        //获取用户开考的时间
        String kkshij = request.getParameter("kkshij");

        //获取这套卷子的题数
        String tote = request.getParameter("tote");

        //获取是自测还是考试
        String ptype = request.getParameter("ptype");

        //获取试卷的ID
        String shijId= request.getParameter("shijId");

        //获取这些题目是否有父级
        String shifyfj = request.getParameter("shifyfj");

        //获取试卷名称
        String topic = request.getParameter("shujmc");
        User user = (User) request.getSession().getAttribute("user");
        //为考试表添加记录
        Exam exam = new Exam();
        exam.setPagerid(Integer.parseInt(shijId));
        exam.setStarttime(kkshij);
        //用户Id
        exam.setTeacherid(user.getUid());
        exam.setTesttime(kkshij);
        exam.setEtype(Integer.parseInt(ptype));
        int ii= examService.insertExam(exam);

        //为个人考试记录表添加信息
        //登录来了从作用域掉用户ID
        int cjr = user.getUid();

        //获取题目编号
        String[] testrescordids = request.getParameterValues("testrescordid");

        //获取用户选中的答案
        String[] chooseanswers = request.getParameterValues("chooseanswer");

        //获取题目的章节知识点编号
        String[] section=request.getParameterValues("knowledgeid");

        //获取题目的一级知识点编号
        String[] knowledgeone=request.getParameterValues("knowledgeid");

        //获取题目的二级知识点编号
        String[] knowledgeid=request.getParameterValues("knowledgeid");

        //获取这些题目是否有父级
        String shifyfjyy = request.getParameter("shifyfj");

        int zhishidbh=10086;
        if(shifyfjyy!=""){
            zhishidbh = Integer.parseInt(shifyfjyy);
        }

        //获取用户做了多少题目
        int ztshu = Integer.parseInt(tote);
        for (int i = 0; i < testrescordids.length; i++) {
            String testrescordid = testrescordids[i]; //第几题的编号
            String chooseanswer = chooseanswers[i]; //第几题的答案
            if(chooseanswers[i]=="" || chooseanswers[i]==null){
                ztshu = ztshu-1;
            }
        }

        //获取用户是主动提交的还是自动提交的
        String zdonhzd = request.getParameter("zdonhzd");

        TestrecordService testrecordService = new TestrecordService();
        Testrecord testrecord = new Testrecord();
        testrecord.setSid(cjr);
        testrecord.setExamid(ii);
        testrecord.setStarttime(kkshij);
        testrecord.setAnswersum(ztshu);
        testrecord.setScore(0);
        testrecord.setTerrace(user.getUid());
        testrecord.setPattern(Integer.parseInt(zdonhzd));
        testrecord.setCorrect(0);
        testrecord.setSubmit(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        int iii = testrecordService.insertTestrecord(testrecord);

        //为考试答题表添加信息并将答对的题目数量保存到个人考试记录表中
        for (int i = 0; i < testrescordids.length; i++) {
            String testrescordid = testrescordids[i]; //第几题的编号
            String chooseanswer = chooseanswers[i]; //第几题的答案
            ExamanwerService examanwerService = new ExamanwerService();
            Examanwer examanwer = new Examanwer();
            examanwer.setTestrescordid(iii);
            examanwer.setPagerqustionid(Integer.parseInt(testrescordids[i]));
            examanwer.setChooseanswer(chooseanswers[i]);
            QuestionService questionService = new QuestionService();
            Question question = questionService.selectAnswer(Integer.parseInt(testrescordids[i]));
            examanwer.setRightanswers(question.getAnswer());
            examanwerService.insertExamanwerDao(examanwer);
        }

        //查询用户答对了几题
        ExamanwerService examanwerService = new ExamanwerService();
        int correct = examanwerService.selectCorrect(iii);

        //答对题数查出来后对考试记录表的对题数量进行修改
        testrecordService.updateTestrecord(correct,iii);

        //为个人刷题记录表添加信息
        ExamanwerDaoImpl examanwerDao = new ExamanwerDaoImpl();
        List<Examanwer> list =examanwerDao.selectBctim(iii);
        String shuzu="";
        for (Examanwer examanwer : list) {
            if(!examanwer.getChooseanswer().isEmpty()){
                examanwer.setPagerqustionid(examanwer.getPagerqustionid());
                shuzu = String.valueOf(examanwer.getPagerqustionid());
                QuestionDaoImpl questionDao = new QuestionDaoImpl();
                Question question = questionDao.selectTyp(Integer.parseInt(shuzu));
                System.out.println(shuzu);
                System.out.println(question.getKnowledgetwo());
                RecordService recordService = new RecordService();
                int i = recordService.selectRecord(question.getKnowledgetwo());
                System.out.println(i);
                if(zhishidbh!=0){
                    if(i>0){
                        int iy = recordService.updateRecordlist(Integer.parseInt(shuzu), String.valueOf(question.getKnowledgetwo()));
                        System.out.println(iy);
                    }else{
                        Record record = new Record();
                        record.setSection(question.getSection());
                        record.setKnowledgeone(question.getKnowledgeone());
                        record.setKnowledgeid(question.getKnowledgetwo());
                        record.setPercentum(0);
                        record.setSid(user.getUid());
                        record.setRecordlist(shuzu);
                        recordService.insertRecord(record);
                    }

                    //计算单元知识点的答题进度
                    int iop = questionDao.selectTmshul(question.getKnowledgetwo());
                    int mytddfb=100/iop;
                    RecordDaoImpl recordDao = new RecordDaoImpl();
                    Record record = recordDao.selectTmu(question.getKnowledgetwo());
                    String[] recordlistArray = record.getRecordlist().split(",");
                    System.out.println("recordlistArray.length = " + recordlistArray.length);
                    System.out.println("iop==recordlistArray.length  " + (iop==recordlistArray.length));
                    if(iop==recordlistArray.length){
                        System.out.println("100----------");
                        recordDao.updateCompleteness(100,question.getKnowledgetwo());
                    }else {
                        System.out.println("66----------");
                        int jishu = mytddfb*recordlistArray.length;
                        recordDao.updateCompleteness(jishu,question.getKnowledgetwo());
                    }
                }
            }
        }
        request.setAttribute("list",iii);
        request.setAttribute("topic",topic);
        response.sendRedirect("ExamanwerServlet?list="+iii);
       // request.getRequestDispatcher("ExamanwerServlet").forward(request,response);
    }
}